<template>
  <div class="upload-container">
    <el-button
      type="primary"
      icon="el-icon-upload"
      size="mini"
      :style="{ background: color, borderColor: color }"
      @click=" dialogVisible=true"
    >
      上传图片
    </el-button>

    <el-dialog title="上传图片" center append-to-body :visible.sync="dialogVisible">
      <el-upload
        class="editor-slide-upload"
        action=""
        list-type="picture-card"
        :multiple="true"
        :http-request="uploader"
        :file-list="fileList"
        :show-file-list="true"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
      >
        <el-button size="small" type="primary">
          将文件拖到此处，或点击上传
        </el-button>
      </el-upload>

      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import imageCompression from 'browser-image-compression'

// 图片文件类型正则
const FILE_TYPE_REG = /^image\/(jpg|jpeg|png)$/
// 图片压缩配置
const IMAGE_COMPRESSION_CONFIG = {
  maxSizeMB: 1,
  maxWidthOrHeight: 1920,
  useWebWorker: true
}

export default {
  name: 'EditorSlideUpload',

  props: {
    color: {
      type: String,
      default: '#1890ff'
    },

    path: {
      type: String,
      default: ''
    },

    service: {
      type: Function
    }
  },

  data() {
    return {
      dialogVisible: false,
      listObj: {},
      fileList: []
    }
  },

  methods: {
    /**
     * 检查是否全部上传完成
     */
    checkAllSuccess() {
      return Object.keys(this.listObj).every(item => this.listObj[item].hasSuccess)
    },

    /**
     * 确认处理方法
     */
    handleSubmit() {
      const arr = Object.keys(this.listObj).map(v => this.listObj[v])
      if (!this.checkAllSuccess()) {
        this.$message('请等待所有图片上传成功。如果出现网络问题，请刷新页面重新上传!')
        return
      }
      this.$emit('success', arr)
      this.listObj = {}
      this.fileList = []
      this.dialogVisible = false
    },

    /**
     * 上传成功处理方法
     */
    handleSuccess(response, file) {
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          this.listObj[objKeyArr[i]].url = response
          this.listObj[objKeyArr[i]].hasSuccess = true
          return
        }
      }
    },

    /**
     * 移除处理方法
     */
    handleRemove(file) {
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          delete this.listObj[objKeyArr[i]]
          return
        }
      }
    },

    /**
     * 上传前处理方法
     */
    beforeUpload(file) {
      if (!file || !FILE_TYPE_REG.test(file.type)) {
        this.$message.error('请选择 JPG 或 PNG 格式的图片')
        return false
      }

      const _self = this
      const _URL = window.URL || window.webkitURL
      const fileName = file.uid
      this.listObj[fileName] = {}
      return new Promise((resolve, reject) => {
        const img = new Image()
        img.src = _URL.createObjectURL(file)
        img.onload = function() {
          _self.listObj[fileName] = { hasSuccess: false, uid: file.uid, width: this.width, height: this.height }
        }
        resolve(true)
      })
    },

    /**
     * 上传
     */
    async uploader({ file }) {
      if (!(file instanceof Blob)) {
        this.$message.error('图片选择异常')
        throw new TypeError('图片选择异常')
      }
      if (typeof this.service !== 'function') {
        this.$message.error('图片上传异常')
        return Promise.reject('未定义图片上传方法')
      }

      // 图片压缩
      let compressedFile
      try {
        compressedFile = await imageCompression(file, IMAGE_COMPRESSION_CONFIG)
      } catch (error) {
        console.error('图片压缩异常：', error)
        this.$message.error('图片压缩失败')
        throw new Error('图片压缩失败')
      }

      // 图片上传
      try {
        const [data] = await this.service({ file: compressedFile, path: this.path })
        return data
      } catch (error) {
        console.error('图片上传异常：', error)
        this.$message.error('图片上传失败')
        throw error
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.editor-slide-upload {
  margin-bottom: 20px;

  ::v-deep .el-upload--picture-card {
    width: 100%;
  }
}
</style>
